<template>
  <div class="history">
    <scroll-view scroll-y="true" class="scroll-Y" @scrolltolower="onReachBottom">
      <view class="history-empty" v-if="historylist.length == 0">
        <image src="/static/tabs/zanwushuju.png" mode="scaleToFill" />
        <view class="history-empty-title">你还没有制作过作品哦</view>
        <view class="history-empty-text">快去制作吧！</view>
        <view class="history-empty-but" @click="gohome">立即制作</view>
      </view>
      <view class="history-box" v-else>
        <view class="history-box-title">
          <text>近7日作品</text>
          <text @click="maskflag = true" v-if="!maskflag">选择</text>
          <text @click="cancel" v-else>取消</text>
        </view>
        <view class="history-box-list">
          <view class="history-box-list-item" v-for="item in historylist" :key="item.id">
            <image :src="item.thuImgUrl" mode="aspectFill" @click="godetail(item)" />
            <image src="/static/tabs/dh.png" class="dh" mode="scaleToFill" v-if="item.status == 2" />
            <view class="lodeing" v-if="item.status == 2">正在创作中...</view>
            <view class="mask" v-if="maskflag">
              <view v-if="item.flag == false" @click="item.flag = true"></view>
              <image v-else src="/static/tabs/zhengque.png" mode="scaleToFill" @click="item.flag = false" />
            </view>
          </view>
          <view class="history-box-list-but" v-if="maskflag" @click="delitem">
            <image src="/static/tabs/shanchu.png" mode="scaleToFill" />
            <text>确定删除</text>
          </view>
        </view>
      </view>
    </scroll-view>
  </div>
</template>

<script lang="ts" setup>
import { ref, reactive } from "vue";
import { onLoad, onShow, onUnload, onReady, onTabItemTap } from "@dcloudio/uni-app"
import { GetUserImageRecord, UploadImagetep, DeleteImageInfo } from '@/api/user'
import { useUserStore } from '@/stores'
const userStore = useUserStore()
const maskflag = ref(false)
const historylist = ref<any>([]);
const Page = ref(1)
const Limit = ref(10)
const total = ref(0)
const punti = ref(0)
const lonflag = ref(false)
const state = reactive<any>({
  timeInter: null,//定义定时器
})
onLoad(() => {
  // if (userStore.userInfo?.token) {
  //   gethistorylist()
  // }
})
onShow(() => {
  if (userStore.userInfo?.token) {
    if (wx.getStorageSync('flag') != true) {
      gethistorylist()
    } else {
      wx.removeStorageSync('flag');
    }
  }
})
onUnload(() => {
  clearInterval(state.timeInter)
  state.timeInter = null
})
const godetail = (item) => {
  wx.setStorageSync('flag', true);

  let obj = JSON.stringify(item)
  uni.navigateTo({
    url: `/pages/detail/index?item=${obj}&punti=${punti.value}`
  })
}
const gohome = () => {
  uni.switchTab({
    url: `/pages/home/index`
  })
}
const gethistorylist = async () => {
  Page.value = 1
  let res: any = await GetUserImageRecord({
    Page: Page.value,
    Limit: Limit.value
  })
  if (res.code == '0') {
    total.value = res.data.total
    punti.value = res.data.punti
    historylist.value = res.data.list.map((item: any) => (
      {
        ...item,
        flag: false,
      }
    ))
    if (historylist.value.some((item: any) => item.status === 2)) {
      state.timeInter = setInterval(() => {
        getCheckComfyUI()
      }, 5000)
    }
  }
}
//定时加载
const getCheckComfyUI = async () => {
  const res: any = await GetUserImageRecord({
    Page: 1,
    Limit: Limit.value
  })
  if (res.code == '0') {
    const list = res.data.list.map((item: any) => ({
      ...item,
      flag: false,
    }))
    if (historylist.value.some((item: any) => item.status === 2)) {
      // 使用 for 循环来替换 img 属性  
      for (let i = 0; i < list.length; i++) {
        historylist.value[i] = list[i]
      }
    } else {
      console.log('没有找到状态为2的元素');
      clearInterval(state.timeInter)
      state.timeInter = null
    }
  }
}
const cancel = () => {
  maskflag.value = false
  historylist.value.forEach(item => { item.flag = false; });
}
const delitem = () => {
  uni.showModal({
    title: '提示',
    content: '删除的记录不可恢复哦',
    cancelText: '取消',
    confirmText: '确认删除',
    success: async function (res) {
      if (res.confirm) {
        console.log('用户点击确定');
        const result = historylist.value.filter(item => item.flag).map(item => item.id).join(", ");
        if (result) {
          let res = await DeleteImageInfo({
            StrId: result
          })
          if (res.code == '0') {
            uni.showToast({
              title: '删除成功',
              duration: 2000,
              icon: 'none'
            })
            gethistorylist()
            cancel()
          }
        }
      } else if (res.cancel) {
        console.log('用户点击取消');
      }
    }
  });
}
const onReachBottom = async () => {
  Page.value += 1
  if (total.value > historylist.value.length) {
    lonflag.value = true
    const res: any = await GetUserImageRecord({
      Page: Page.value,
      Limit: Limit.value
    })
    if (res.code == '0') {
      lonflag.value = false
      total.value = res.data.total
      let List = res.data.list.map((item: any) => (
        {
          ...item,
          flag: false,
        }
      ))
      historylist.value.push(...List)
    }
  }
}
// 相册上传
const uplodimg = () => {
  if (!userStore.userInfo?.token) {
    uni.showToast({
      title: '请先登录～',
      duration: 2000,
      icon: 'none'
    })
    return
  }
  uni.chooseImage({
    count: 1, //默认9
    sizeType: ['original', 'compressed'], //可以指定是原图还是压缩图，默认二者都有
    sourceType: ['album'], //从相册选择
    success: function (res) {
      convertToBase64(res.tempFilePaths[0])
    }
  });
}
function convertToBase64(filePath: any) {
  uni.showLoading({
    title: '上传中'
  });
  const fs = uni.getFileSystemManager(); // 获取文件系统管理器  
  fs.readFile({
    filePath: filePath, // 要读取的文件路径  
    encoding: 'base64', // 以Base64编码读取文件  
    success: async (result) => {
      const base64Data = result.data; // 获取Base64编码的字符串  
      // console.log('Base64编码的图片数据:', base64Data);
      let res: any = await UploadImagetep({
        img: base64Data
      })
      // console.log(res, 'akjsndiowsugdfuiwerhb');
    },
    fail: (err) => {
      console.error('读取文件失败:', err);
    }
  });
}
</script>

<style lang="scss" scoped>
page {
  background-color: #F7F7F7;
}

.history {
  width: calc(100% - 64rpx);
  height: 100%;
  margin: 0 32rpx;

  .scroll-Y {
    height: 100vh;
  }

  &-box {
    width: 100%;
    // margin-top: 30rpx;
    height: 100%;

    &-title {
      display: flex;
      justify-content: space-between;
      width: calc(100% - 64rpx);
      height: 50rpx;
      padding-top: 30rpx;
      position: fixed;
      top: 0rpx;
      left: 32rpx;
      z-index: 9;
      background-color: #fff;

      text {
        display: block;
        font-size: 32rpx;
      }

      text:last-child {
        color: #666;
      }
    }

    &-list {
      margin-top: 100rpx;
      width: 100%;
      // height: 100%;
      // height: calc(100vh - 100rpx);
      display: flex;
      justify-content: space-between;
      flex-wrap: wrap;
      // margin-top: 20rpx;
      // padding-bottom: 100rpx;
      // overflow-y: auto;
      // overflow-x: hidden;

      &-item {
        width: calc(50% - 10rpx);
        height: 600rpx;
        margin-bottom: 15rpx;
        border-radius: 10rpx;
        position: relative;
        background: #f7f7f7;
        overflow: hidden;

        .lodeing {
          width: 100%;
          text-align: center;
          position: absolute;
          top: 50%;
          left: 50%;
          transform: translate(-50%, -50%);
          font-size: 32rpx;
          color: #666;
        }

        image {
          width: 100%;
          height: 100%;
          border-radius: 10rpx;
        }

        .dh {
          width: 100%;
          height: 80rpx !important;
          position: absolute;
          top: -80rpx;
          left: 0;
          width: 100%;
          animation: box 3s infinite linear;
          border-radius: 0 !important;

          @keyframes box {
            from {
              top: -80rpx;
            }

            to {
              top: 100%;
            }
          }
        }

        .mask {
          width: 100%;
          height: 100%;
          position: absolute;
          top: 0;
          left: 0;
          background: rgb(0, 0, 0, 0.3);
          border-radius: 10rpx;

          view {
            width: 30rpx;
            height: 30rpx;
            border-radius: 50%;
            border: 1rpx solid #fff;
            position: absolute;
            top: 20rpx;
            right: 20rpx;
          }

          image {
            width: 32rpx;
            height: 32rpx;
            border-radius: 50%;
            position: absolute;
            top: 20rpx;
            right: 20rpx;
          }
        }
      }

      &-but {
        position: fixed;
        bottom: 0;
        left: 0;
        width: 100%;
        height: 90rpx;
        text-align: center;
        font-size: 32rpx;
        color: rgb(0, 0, 0, 0.9);
        font-weight: 600;
        display: flex;
        justify-content: center;
        background-color: rgb(255, 255, 255, 0.6);

        text {
          line-height: 90rpx;
          height: 90rpx;
          display: block;
          margin-left: 5rpx;
        }

        image {
          width: 40rpx;
          height: 40rpx;
          margin-top: 24rpx;
        }
      }
    }

  }

  &-empty {
    width: 100%;
    text-align: center;
    margin-top: 200rpx;

    image {
      width: 200rpx;
      height: 133rpx;
    }

    &-title {
      font-size: 36rpx;
      color: #666;
      margin-top: 30rpx;
    }

    &-text {
      font-size: 32rpx;
      color: #666;
    }

    &-but {
      width: 400rpx;
      height: 90rpx;
      background: linear-gradient(45deg, #fffacd, #ffdd99, #ffcce6);
      border-radius: 50rpx;
      line-height: 90rpx;
      font-size: 36rpx;
      font-weight: 600;
      margin: 150rpx auto 0;
    }
  }
}
</style>